import React, { useCallback } from 'react';
import { EyeInvisibleOutlined, LogoutOutlined, UserOutlined } from '@ant-design/icons';
import { Avatar, Col, Menu, Row, Spin } from 'antd';
import { history, useModel } from 'umi';
import { stringify } from 'querystring';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';
import type { MenuInfo } from 'rc-menu/lib/interface';
import { logout } from '@/services/cpasRequest';
import { intl } from '@/utils';
import { removeToken } from '@/services/auth';
import { AudTabPage } from '../PageTab';

/**
 * 退出登录，并且将当前的 url 保存
 */
const loginOut = async () => {
  AudTabPage.getInstance().closeTab('closeAll');
  removeToken();
  history.push(`/`); // 不知道为什么，退出时会触发protable的请求，后期得研究下 protable的原理
  await logout();
  localStorage.removeItem('loginInfo');
  const { query = {}, pathname } = history.location;
  const { redirect } = query;
  // Note: There may be security issues, please note
  if (window.location.pathname !== '/user/login' && !redirect) {
    history.push({
      pathname: '/user/login',
      search: stringify({
        redirect: pathname,
      }),
    });
  }
};

const AvatarDropdown: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');

  const onMenuClick = useCallback(
    (event: MenuInfo) => {
      const { key } = event;
      if (key === 'info') {
        return;
      }
      if (key === 'logout') {
        setInitialState((s) => ({ ...s, curUser: undefined }));
        loginOut();
        return;
      }
      history.push(`/${key}`);
    },
    [setInitialState],
  );

  const loading = (
    <span className={`${styles.action} ${styles.account}`}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState) {
    return loading;
  }

  const { curUser } = initialState;

  if (!curUser || !curUser.username) {
    return loading;
  }

  const menuHeaderDropdown = (
    <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
      {/* {menu && <Menu.Divider />} */}
      <Menu.Item key="info">
        <Row align="middle" wrap={false} style={{ width: '230px', height: '80px' }}>
          <Col span={9} style={{ textAlign: 'center' }}>
            <span
              onClick={() => {
                history.push('/');
              }}
            >
              <Avatar size={50} icon={<UserOutlined />} alt="avatar" />
            </span>
          </Col>
          <Col>
            <span style={{ fontSize: 14 }}>
              【{curUser.usercode}】{curUser.username}
            </span>
            <br />
            <span style={{ fontSize: 12, display: 'inline-block', color: '#595959' }}>
              {intl('rc.ap.sysRole', '角色')}：{curUser.rolename}
            </span>
            <br />
            <span style={{ fontSize: 12, color: '#595959' }}>
              {intl('rc.ap.job', '职务')}：{curUser.zw}
            </span>
          </Col>
        </Row>
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item key="changePassword">
        <EyeInvisibleOutlined />
        {intl('rc.ap.changePassword', '修改密码')}
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item key="logout">
        <LogoutOutlined />
        {intl('rc.ap.exit', '退出登录')}
      </Menu.Item>
    </Menu>
  );
  return (
    <HeaderDropdown overlay={menuHeaderDropdown}>
      <span className={`${styles.action} ${styles.account}`}>
        <Avatar
          size="small"
          className={styles.avatar}
          src={curUser.avatar}
          icon={<UserOutlined />}
          alt="avatar"
        />
        <span className={`${styles.name} anticon`}>{curUser.username}</span>
      </span>
    </HeaderDropdown>
  );
};

export default AvatarDropdown;
